import { createApp } from 'vue'
import { createPinia } from 'pinia'
import ElementPlus from 'element-plus'
import 'element-plus/dist/index.css'
import App from './App.vue'
import router from './router'
import api from './api'
import { useAppStore } from './store'

const app = createApp(App)
app.use(createPinia())
app.use(ElementPlus)
app.use(router)

// 应用初始化时检查token并获取用户信息
const store = useAppStore()
const token = localStorage.getItem('token')
if (token) {
  // 尝试获取当前用户信息
  api.get('/auth/me')
    .then(response => {
      if (response.user) {
        store.setUser({
          id: response.user.id,
          username: response.user.username,
          email: response.user.email,
          is_admin: response.user.is_admin || false
        })
      }
    })
    .catch(() => {
      // token无效，清除登录状态
      localStorage.removeItem('token')
      store.setUser(null)
    })
}

app.mount('#app')